package com.guyaogg.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guyaogg.common.utils.R;
import com.guyaogg.gulimall.cart.feign.ProductFeignService;
import com.guyaogg.gulimall.cart.interceptor.CartInterceptor;
import com.guyaogg.gulimall.cart.service.CartService;
import com.guyaogg.gulimall.cart.vo.Cart;
import com.guyaogg.gulimall.cart.vo.CartItem;
import com.guyaogg.gulimall.cart.vo.SkuInfoVO;
import com.guyaogg.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author 顾遥
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    private final String CART_PREFIX = "gulimall:cart:";

    private final StringRedisTemplate redisTemplate;
    private final ProductFeignService productFeignService;
    private final ThreadPoolExecutor executor;

    public CartServiceImpl(StringRedisTemplate redisTemplate, ProductFeignService productFeignService, ThreadPoolExecutor executor) {
        this.redisTemplate = redisTemplate;
        this.productFeignService = productFeignService;
        this.executor = executor;
    }

    @Override
    public void addToCart(Long skuId, Integer count) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> carOpts = getCartOperations();

        // 一。添加旧商品
        String res = (String) carOpts.get(skuId.toString());
        if (!ObjectUtils.isEmpty(res)) {
            // 购物车有此商品
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            // 更新数量
            cartItem.setCount(cartItem.getCount() + count);
            carOpts.put(skuId.toString(), JSON.toJSONString(cartItem));
            return;
        }

        // 二.添加新商品
        CartItem cartItem = new CartItem();

        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            // 1.远程查询当前要添加的信息
            R r = productFeignService.getSkuInfo(skuId);
            SkuInfoVO data = r.getData("skuInfo", new TypeReference<SkuInfoVO>() {
            });
            // 2.将商品添加到购物车
            cartItem.setCheck(true);
            cartItem.setCount(count);
            cartItem.setImage(data.getSkuDefaultImg());
            cartItem.setTitle(data.getSkuTitle());
            cartItem.setSkuId(skuId);
            cartItem.setPrice(data.getPrice());
        },executor);

        CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
            // 3.远程查询 sku 的组合信息
            List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttr(values);
        },executor);
        // 等待异步任务完成
        CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();

        // 封装进 redis
        String jsonString = JSON.toJSONString(cartItem);
        carOpts.put(skuId.toString(), jsonString);
    }

    @Override
    public CartItem getCartItem(Long skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOperations();
        String json = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(json, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tempKey = CART_PREFIX + userInfoTo.getUserKey();

        // 拿到购物车绑定
        if (userInfoTo.getUserId() != null) {
            // 1.登录
            // 2.如果临时购物车的数据还没有合并
            List<CartItem> tempCartItems = getCartItems(tempKey);
            if(tempCartItems != null){
                // 临时购物车不为空,需要合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 3) 删除临时购物车
                clearCart(tempKey);
            }

            // 3.获取登录后的购物车数据
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);


        } else {
            // 2.未登录

            // 获取临时购物车数据
            cart.setItems(getCartItems(tempKey));
        }
        return cart;
    }
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);


    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOperations();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), jsonString);

    }

    @Override
    public void changeCountItem(Long skuId, Integer count) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOperations();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(count);
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), jsonString);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOperations();
        cartOps.delete(skuId.toString());

    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() == null){
            return null;
        }
        String cartKey = CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);

        assert cartItems != null;

        return cartItems.stream().filter(CartItem::getCheck).peek(item -> {
            // TODO 更新为最新价格
            BigDecimal price = productFeignService.getPrice(item.getSkuId());
            // 更新为最新价格
            item.setPrice(price);
        }).collect(Collectors.toList());
    }

    /**
     * 获取我们要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOperations() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        // 1.指定存储主键
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            // 登录了
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // redis 绑定购物车 key
        return redisTemplate.boundHashOps(cartKey);

    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (values != null && values.size() > 0) {
            return values.stream().map(obj -> JSON.parseObject((String) obj, CartItem.class)).collect(Collectors.toList());
        }
        return null;
    }
}
